<?php


namespace app\common\cachemodel;


use app\common\lib\exception\ApiException;
use app\common\model\BaseCache;
use think\Cache;
use XznsTools\cache\CacheManage;

class ZlcrCustomReportGoods extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr_custom_report_goods';

    protected $cacheModel = 'custom_report.question_goods';

    public $custom_report_goods_index_num_cache = 'custom_report_goods';

    /**
     * 缓存获取当前用户已支付的报告信息
     * @param int $type 1=>热门问题，2=>全部问题
     * @return array
     * @throws \Exception
     */
    public function getQuestionGoodsFromCache($type)
    {
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $type)->setSort('desc')->ZsGetIocData('list', function () use ($type)
        {
            return $this->getQuestionGoodsIdsFromDms($type);
        });
        return [
            'ids' => $ids,
            'data' => $this->batchGetInfoByIds($ids)
        ];
    }

    /**
     * 数据库获取当前用户的报告id
     * @param int $type 1=>热门问题，2=>全部问题
     * @return array
     */
    public function getQuestionGoodsIdsFromDms($type)
    {
        if ($type == 1)
        {
            $where = ['g.status' => 1, 'g.is_hot' => 1, 't.status' => 1];
        } else
        {
            $where = ['g.status' => 1, 't.status' => 1];
        }

        try
        {
            $ids = $this
                ->alias('g')
                ->join('wechat_backup_07_18_14_43_00.zlcr_tag t', 'g.tid=t.id')
                ->where($where)
                ->column('g.sort', 'g.id');
        }
        catch (\Exception $e)
        {
            $ids = [];
        }
        arsort($ids);
        return $ids;
    }


    /**
     * 获取所有问题并重组
     * @param $ids
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function getQuestionAllsResrt($ids, $data)
    {
        $customData = [];
        $resData = [];
        $tagModel = new ZlcrTag();
        $tag = $tagModel->getLevelTag(1, 0);
        if ($data)
        {
            foreach ($ids as $value)
            {
                if (!isset($data[$value]['qtype']) || !isset($tag[$data[$value]['tid']]['tag_name']))
                {
                    continue;
                }
                if (!isset($resData[$data[$value]['tid']]) && $data[$value]['qtype'] == 1)
                {
                    $resData[$data[$value]['tid']] = [
                        'tab_name' => $tag[$data[$value]['tid']]['tag_name'],
                        'data_list' => []
                    ];
                }
                $report_list = [
                    'gid' => (int)$data[$value]['id'],
                    'question_name' => $data[$value]['question_name'],
                    'is_merge' => (int)$data[$value]['is_merge'],
                    'price' => (int)$data[$value]['price'],
                    'question_type' => (int)$data[$value]['qtype'],
                ];
                if ($data[$value]['qtype'] == 1)
                {   // 固定报告
                    $resData[$data[$value]['tid']]['data_list'][] = $report_list;
                } else
                {   // 自定义报告
                    $customData[] = $report_list;
                }
            }
        }

        if ($customData)
        {
            foreach ($resData as $tid => $item)
            {
                $resData[$tid]['data_list'] = array_merge($item['data_list'], $customData);
            }
        }

        $arr = [];
        if ($resData)
        {
            foreach ($tag as $key => $item)
            {
                if (isset($resData[$key]))
                {
                    $arr[$key] = $resData[$key];
                }
            }
        }
        return $resData ? array_values($arr) : [];
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     * @throws ApiException
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $where = ['id' => ['in', $ids]];
            } else
            {
                $where = ['status' => 1];
            }
            $data = $this
                ->where($where)
                ->order('sort ', $sortType)
                ->column('question_name,tid,is_merge,qtype,price,description,is_hot,example_url,remark,sort,status,required_temp,option_temp,extend', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 获取首页报告商品数量
     * @return array
     * @throws \Exception
     */
    public function getGoodsIndexNum()
    {
        $customReportInfo = (new AppConfig())->configInfo('custom_report');
        $switch = $customReportInfo['index_goods_num_switch'];
        if ($switch)
        {
            $num = Cache::get($this->custom_report_goods_index_num_cache . date('Ymd'));
            //数量初始化
            if ($num === false)
            {
                Cache::set($this->custom_report_goods_index_num_cache . date('Ymd'), $customReportInfo['index_goods_num'], 86400);
                $num = $customReportInfo['index_goods_num'];
            }
            if ($num > 0)
            {
                $numInfo = $num;
            } else
            {
                $numInfo = 0;
            }
        }
        return [
            'switch' => $switch,
            'total' => $customReportInfo['index_goods_num'] ?? 0,
            'num' => $numInfo ?? 0,
            'base_unlock_num' => $customReportInfo['base_unlock_num'] ?? 0,
            'is_show_icon' => $customReportInfo['is_show_icon'] ?? 0,
        ];
    }

    /**
     * 首页报告商品数量还原
     * @throws \Exception
     */
    public function resetGoodsIndexNum()
    {
        $indexNum = $this->getGoodsIndexNum();
        if ($indexNum['switch'] && $indexNum['num'] < $indexNum['total'])
        {
            Cache::set($this->custom_report_goods_index_num_cache . date('Ymd'), $indexNum['num'] + 1, 86400);
        }
    }
}
